package com.px.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.px.config.AlipayConfig;
import com.px.pojo.ShOrder;
import com.px.service.PayService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/api/v/pay")
public class PayController {


    @Resource
    private PayService payService;

    @Resource
    private AlipayConfig alipayConfig;

    //调用支付宝支付页面
    @RequestMapping("/toPay")
    public void toPay(@RequestParam(defaultValue = "4") Integer orderId, HttpServletResponse response) throws Exception{
        String form = payService.createAliForm(orderId);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    //同步通知
    @RequestMapping("/callBack")
    public String callBack(HttpServletRequest request) throws Exception{
        //1、验签
        boolean success = payService.validateAliPay(request.getParameterMap());
        if (success){
            //获取用户的订单号
            String outTradeNo = request.getParameter("out_trade_no");
            //获取支付宝交易号
            String tradeNo = request.getParameter("trade_no");
            //判断交易记录表中是否有该订单的交易
            ShOrder shOrder = payService.selectOrderByOrderNo(outTradeNo);
            if (!payService.validateDealPaySuccess(outTradeNo)){
                payService.dealPaySuccess(outTradeNo,tradeNo,1);
            }
            return "redirect:"+alipayConfig.getPaymentSuccessUrl();
        }
        return "redirect:"+alipayConfig.getPaymentFailureUrl();
    }


    //异常通知
    @RequestMapping("/payNotify")
    public void payNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=UTF-8");
        boolean signVerified = payService.validateAliPay(request.getParameterMap());
        if (signVerified){
            String orderNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            String tradeStatus = new String(request.getParameter("trade_Status").getBytes("ISO-8859-1"),"UTF-8");
            if (tradeStatus.equals("TRADE_FINISHED")){
                if (!payService.validateDealPaySuccess(orderNo)){
                    payService.dealPaySuccess(orderNo,tradeNo,1);
                }else if (tradeStatus.equals("TRADE_SUCCESS")){
                    if (!payService.validateDealPaySuccess(orderNo)){
                        payService.dealPaySuccess(orderNo,tradeNo,1);
                    }
                }
                response.getWriter().println("success");
            }else {
                response.getWriter().println("fail");
            }
            response.getWriter().close();
        }
    }

    //退款
    @RequestMapping("/payReFund")
    public String payReFund(@RequestParam(defaultValue = "2") Integer orderId) throws Exception{
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getUrl(),
                alipayConfig.getAppID(),
                alipayConfig.getRsaPrivateKey(),
                alipayConfig.getFormat(),
                alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(),
                alipayConfig.getSignType());
        AlipayTradeRefundRequest req = new AlipayTradeRefundRequest();
        String out_request_no = "HZ01RF001";
        ShOrder shOrder = payService.selectOrderById(orderId);
        if (shOrder.getPayStatus()==1){
            JSONObject bizContent = new JSONObject();
            bizContent.put("trade_no", shOrder.getAliTradeNo());
            bizContent.put("refund_amount", shOrder.getAmount());
            bizContent.put("out_request_no", out_request_no);
            req.setBizContent(bizContent.toString());
            AlipayTradeRefundResponse res = alipayClient.execute(req);
            if(res.isSuccess()){
                payService.dealPaySuccessReFund(shOrder.getOrderNo(),shOrder.getAliTradeNo());
                return "payReFund";
            } else {
                return "NoPayReFund";
            }
        }else {
            return "NoPayReFund";
        }
    }

}
